package gamemodel.clock;

public class RollOverCounter {
	
	private Counter hour; //represents the hour hand of a clock
	private Counter minute; //represents the minute hand of a clock
	private Counter second; //represents the second hand of a clock
	
	//static constants representing default hour, minute, and second values
	public static int DEFAULT_HOUR = 0; 
	public static int DEFAULT_MINUTE = 5; 
	public static int DEFAULT_SECOND = 60; 
	
	public RollOverCounter(int hour, int minute, int second){
		//error check
		if (hour < 0){
			hour = DEFAULT_HOUR; 
		}
		if (minute < 0){
			minute = DEFAULT_HOUR; 
		}
		if (second < 0){
			second = DEFAULT_SECOND;
		}
		
		if (minute > 60){
			hour = hour +  minute / 60; 
			minute = minute % 60; 
		}
		
		this.hour = new Counter(hour); 
		this.minute = new Counter(minute); 
		this.second = new Counter(second); 
		
		this.second.setNextCounter(this.minute); 
		this.minute.setNextCounter(this.hour); 
	}
	
	public RollOverCounter(){
		this(DEFAULT_HOUR, DEFAULT_MINUTE, DEFAULT_SECOND);
	}
	
	public RollOverCounter(int minute){
		this(DEFAULT_HOUR, minute, DEFAULT_SECOND); 
	}
	
	/**
	 * Decrements the second hand 
	 */
	public void tick(){
		this.second.decrement();
	}
	
	@Override
	public String toString(){
		StringBuffer sb = new StringBuffer("Currently the time is "); 
		
		int hour = this.hour.getCount();
		int minute = this.minute.getCount() % 60; 
		int second = this.second.getCount() % 60; 
		
		if (hour < 10){
			sb.append(0); 
		}
		sb.append(hour); 
		sb.append(":"); 
		if (minute < 10){
			sb.append(0); 
		}
		sb.append(minute); 
		sb.append(":");
		if (second < 10){
			sb.append(0); 
		}
		sb.append(second); 
		
		return sb.toString(); 
	}
	
	/**
	 * Determines if time has expired
	 * @return true, if there is no longer any time remaining. False otherwise.
	 */
	public boolean isTimeExpired(){
		return this.hour.getCount() == 0 && this.minute.getCount() == 0 && this.second.getCount() == 0; 
	}
	
	public static void main(String args[]){
		RollOverCounter rc = new RollOverCounter(5); 
		System.out.println(rc); 
		while (true){
			rc.tick(); 
			System.out.println(rc); 
			if (rc.isTimeExpired()) break;
		}
	}
}
